/*
 *  Copyright 2013 National Institute of Advanced Industrial Science and Technology
 *  
 *  Licensed under the Apache License, Version 2.0 (the "License");
 *  you may not use this file except in compliance with the License.
 *  You may obtain a copy of the License at
 *  
 *      http://www.apache.org/licenses/LICENSE-2.0
 *  
 *  Unless required by applicable law or agreed to in writing, software
 *  distributed under the License is distributed on an "AS IS" BASIS,
 *  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 *  See the License for the specific language governing permissions and
 *  limitations under the License.
 */

package org.sss.util;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.ArrayList;
import java.util.concurrent.Callable;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.FutureTask;

public class Util {
  private Util() {
  }

  public static byte[] readAll(InputStream is) throws IOException {
    ByteArrayOutputStream bos = new ByteArrayOutputStream();
    byte[] buf = new byte[10000];
    int read;
    while ((read = is.read(buf, 0, buf.length))  > 0) {
      bos.write(buf, 0, read);
    }
    return bos.toByteArray();
  }

  public static <T> T orElse(T v, T def) {
    if (v != null) {
      return v;
    }
    else {
      return def;
    }
  }
  
  public static <R, A> List<R> callInParallel(final UnaryCallable<R, A> callback, 
                                            Iterable<A> args
                                            ) throws InterruptedException, ExecutionException {
    Executor executor = ThreadPerTaskExecutor.getInstance();
    List<FutureTask<R>> tasks = new ArrayList<FutureTask<R>>();
    
    for (final A arg: args) {
      FutureTask<R> task = new FutureTask<R>(new Callable<R>() {
        @Override
        public R call() throws Exception {
          return callback.call(arg);
        }
      });
      tasks.add(task);
    }
    
    for (FutureTask<R> task: tasks) {
      executor.execute(task);
    }
    
    List<R> results = new ArrayList<R>();
    for (FutureTask<R> task: tasks) {
      results.add(task.get());
    }
    return results;
  }
}
